###############################################################################
#                           Standard Stuff
################################################################################
AC_INIT([CGMA],[16.0.1],[cgma-dev@mcs.anl.gov],[cgma],[http://sigma.mcs.anl.gov])
AC_CONFIG_MACRO_DIR([config])
AC_CONFIG_AUX_DIR([config])
AC_CANONICAL_SYSTEM
AC_CANONICAL_TARGET
m4_ifdef([AM_SILENT_RULES],
          [m4_define([cgm_am_oldtests], [[color-tests] [parallel-tests]])],
          [m4_define([cgm_am_oldtests], [])])
AM_INIT_AUTOMAKE([subdir-objects] cgm_am_oldtests)
m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])

AC_CHECK_PROG( [SED], [sed], [sed], [true] )

# Infer the source directory as the path to the ./configure script
#srcdir=`dirname $0`
#top_srcdir=`dirname $0`
USER_CONFIGURE_CMD="$0 $ac_configure_args"

AC_ARG_ENABLE([fortran],[AC_HELP_STRING([--disable-fortran],
  [No Fortran name mangling in ITAPS C headers])],
  [ENABLE_FORTRAN=$enableval],[ENABLE_FORTRAN=yes])

AM_PROG_AR
AC_PROG_LN_S
AC_PROG_MAKE_SET
AC_DISABLE_SHARED

FATHOM_CHECK_COMPILERS([yes],[yes],[$ENABLE_FORTRAN])
AM_CONDITIONAL(PARALLEL,[test "x$enablempi" != "xno"])
AM_CONDITIONAL(ENABLE_FORTRAN,[test "x$ENABLE_FORTRAN" != "xno"])
AC_SUBST(enablempi)

# Invoke and find all necessary flags for C, C++, FC
FATHOM_COMPILER_FLAGS([yes],[yes],[$ENABLE_FORTRAN])

AC_PROG_LN_S
AC_PROG_MAKE_SET

LIBS="-lm"
# All language options initialized -- now call
# libtool initialization
# AC_PROG_LIBTOOL is deprecated
LT_INIT([dlopen])

AC_C_BIGENDIAN( [], [AM_CPPFLAGS="$AM_CPPFLAGS -DLITTLE_ENDIAN=BYTE_ORDER"] )

FATHOM_CHECK_CXX_WORKS([], [AC_MSG_ERROR([Cannot build without C++ compiler])])

################################################################################
#                              Version Stuff
################################################################################

# Windows related defines
#AC_DEFINE(CGMA_INIT_EXPORT,[],[CGMA_INIT_EXPORT comment])
#AC_DEFINE(CGMA_GEOM_EXPORT,[],[CGMA_INIT_EXPORT comment])
#AC_DEFINE(CGMA_UTIL_EXPORT,[],[CGMA_INIT_EXPORT comment])
#AC_DEFINE(CGMA_IGEOM_EXPORT,[],[CGMA_INIT_EXPORT comment])

AC_DEFINE(VERSION,["AC_PACKAGE_VERSION"],[CGM Version])
MAJOR_VERSION=`expr AC_PACKAGE_VERSION : '\([[0-9]]*\)'`
MINOR_VERSION=`expr AC_PACKAGE_VERSION : '[[0-9]]*\.\([[0-9]]*\)'`
VERSION_PATCH=`expr AC_PACKAGE_VERSION : '[[0-9]]*\.[[0-9]]*\.\(.*\)'`
test "x" != "x$MAJOR_VERSION" || AC_MSG_ERROR("Invalid version string: AC_PACKAGE_VERSION")
test "x" != "x$MINOR_VERSION" || AC_MSG_ERROR("Invalid version string: AC_PACKAGE_VERSION")
AC_DEFINE_UNQUOTED(MAJOR_VERSION,$MAJOR_VERSION,[CGM Major Version])
AC_DEFINE_UNQUOTED(MINOR_VERSION,$MINOR_VERSION,[CGM Minor Version])
if test "x" != "x$VERSION_PATCH"; then
  AC_DEFINE_UNQUOTED(VERSION_PATCH,$VERSION_PATCH,[CGM Patch Level])
  VERSION_STRING="AC_PACKAGE_STRING"
elif test $MINOR_VERSION -eq 99; then
  VERSION_STRING="AC_PACKAGE_STRING (Alpha)"
else
  VERSION_STRING="AC_PACKAGE_STRING (Beta)"
fi

AC_DEFINE_UNQUOTED(VERSION_STRING,"${VERSION_STRING}",[CGM Version String])
################################################################################
#                Create libtool script
################################################################################
# We need the libtool script both for the calls to the ITAPS_LIBTOOL_VAR
# macro and for us in testing for libraries.  If we're using a newer
# version of libtool, the script normally isn't generated until AC_OUTPUT
# at the end of the configure script.  Ask that it be created now instead.
m4_ifdef([LT_OUTPUT],[LT_OUTPUT])

################################################################################
#                              Extract libtool config
################################################################################
FATHOM_LIBTOOL_VAR( [CXX], [compiler_lib_search_path], [CGM_CXX_LINKFLAGS])
FATHOM_LIBTOOL_VAR( [CXX], [postdeps], [CGM_CXX_LIBS])
AC_SUBST(CGM_CXX_LINKFLAGS)
AC_SUBST(CGM_CXX_LIBS)

################################################################################
#                              MPI OPTIONS
################################################################################

AM_CONDITIONAL(build_parallel, [test "x$enablempi" != "xno"])
#FATHOM_CHECK_MPI
#FATHOM_CONFIG_MPI_EXEC
if test "x$enablempi" != "xno"; then
  AM_CXXFLAGS="$AM_CXXFLAGS -DUSE_MPI"
  CGM_PARALLEL_INCLUDE='-I${CGM_DIR}/src/geom/parallel'
  CGM_PARALLEL_LIB='-L${CGM_DIR}/src/geom/parallel -lcgm_parallel'
  CGM_PARALLEL_LIB_FILE='${CGM_LIBDIR}/libcgm_parallel.la'
fi
AM_CONDITIONAL(USE_MPI, [test "xno" != "x$enablempi"])
AC_SUBST(CGM_PARALLEL_INCLUDE)
AC_SUBST(CGM_PARALLEL_LIB)
AC_SUBST(CGM_PARALLEL_LIB_FILE)
# Used to generate CGMmpi.h
if test "xyes" = "x$MPI_CXX_HELP_NEEDED"; then
  AC_DEFINE( [CGM_MPI_CXX_CONFLICT], [1],
    [MPICH_IGNORE_CXX_SEEK is not sufficient to avoid conflicts] )
  AC_DEFINE_UNQUOTED([CGM_SEEK_SET],[$SEEK_SET],["Value of C SEEK_SET"])
  AC_DEFINE_UNQUOTED([CGM_SEEK_CUR],[$SEEK_CUR],["Value of C SEEK_CUR"])
  AC_DEFINE_UNQUOTED([CGM_SEEK_END],[$SEEK_END],["Value of C SEEK_END"])
fi

################################################################################
#                           CGM-specific Checks
################################################################################

FATHOM_CANT_USE_STD
FATHOM_TEMPLATE_DEFS_INCLUDED
CGM_DEFINES="$CANT_USE_STD $CANT_USE_STD_IO $TEMPLATE_DEFS_INCLUDED"
AM_CPPFLAGS="$AM_CPPFLAGS $CGM_DEFINES"
AM_CONDITIONAL(INCLUDE_TEMPLATE_DEFS, test x$TEMPLATE_DEFS_INCLUDED != x)
AC_SUBST(CGM_DEFINES)

CUBIT_DIR=no
AM_CONDITIONAL(BUILD_CGM,[test "x$CUBIT_DIR" == "xno"])

################################################################################
#                           iGeom Part 1 of 2
################################################################################

FORCE_IGEOM=no
AC_ARG_ENABLE( [igeom],
[AC_HELP_STRING([--disable-igeom],[Do not build support for iGeom interface])],
[FORCE_IGEOM=yes],
[enableval=yes] )

case $enableval in
  yes)
    ENABLE_igeom=yes
    ;;
  nofortran|NoFortran|noFORTRAN|NoFORTRAN|Nofortran)
    AC_MSG_ERROR([Depricated value for --enable-igeom: \"$enableval\".  Try \"FC= F77=\"])
    ;;
  no)
    ENABLE_igeom=no
    ;;
  *)
    AC_MSG_ERROR([Invalid argument to --enable-igeom : $enableval])
    ;;
esac

################################################################################
#                           iGeom Part 2 of 2
################################################################################

AC_MSG_CHECKING([if iGeom support is to be built])
AC_MSG_RESULT([$ENABLE_igeom])
AM_CONDITIONAL([ENABLE_igeom],[test "xyes" = "x$ENABLE_igeom"])

################################################################################
#                           ITAPS shim
################################################################################
AC_ARG_ENABLE([shim],[AC_HELP_STRING([--enable-shim],
  [Enable ITAPS shim])],
  [ITAPS_SHIM=$enableval],[ITAPS_SHIM=no])
AM_CONDITIONAL([ITAPS_SHIM],[test "xyes" = "x$ITAPS_SHIM"])

################################################################################
#                           OCC Options
################################################################################
# Add --with-occ option to configure script

AC_ARG_WITH( occ,
             [AC_HELP_STRING([--with-occ=<dir>],[OpenCascade shared library directory])],
             [occ_DIR="$withval"
              DISTCHECK_CONFIGURE_FLAGS="$DISTCHECK_CONFIGURE_FLAGS --with-occ=\"${withval}\""],
             [occ_DIR=no] )

AC_ARG_ENABLE( dev, 
             [AC_HELP_STRING([--enable-dev],[enable make check to verify *modify* and *makept* testcases in occ build, default: no])],
             [DEV=yes], [DEV=no] )

AM_CONDITIONAL(DEV, test x"$DEV" = x"yes")

# if user specified option (other than --without-occ)
#CGM_OCC_LIB=
HAVE_OCC_DEF=
if test "x$occ_DIR" != "xno"; then
  OCC_CORE_LIBS="-lTKMesh -lTKTopAlgo -lTKGeomAlgo -lTKBRep -lTKGeomBase -lTKG3d -lTKG2d -lTKMath -lTKernel"
  OCC_GEOM_LIBS="-lTKHLR -lTKOffset -lTKShHealing -lTKFillet -lTKFeat -lTKBool -lTKBO -lTKPrim"
  OCC_LCAF_LIBS="-lTKBinL -lTKLCAF -lTKCDF -lTKCAF"
  OCC_LIBS="$OCC_LCAF_LIBS $OCC_GEOM_LIBS $OCC_CORE_LIBS"
  OCC_STEP_LIBS="-lTKSTEP -lTKSTEP209 -lTKSTEPAttr -lTKSTEPBase -lTKXSBase" 
  ISOCE="FALSE"

  # Set OCC_INC_FLAG and OCC_LIB_FLAG based on --with-occ option
  if test "x$occ_DIR" = "x"; then
    OCC_INC_FLAG=
    OCC_LIB_DIR=
    OCC_LIB_FLAG=
  else
    AC_CACHE_CHECK( [for 'include' subdir of $occ_DIR],
                    [ac_cv_occ_include_dir],
                    [ac_cv_occ_include_dir=NONE
                     for subdir in include/oce include/occ include inc ros/inc; do
                       if test -f "${occ_DIR}/${subdir}/Standard_Version.hxx"; then
                         ac_cv_occ_include_dir="$subdir"
                         break
                       elif test -d "${occ_DIR}/${subdir}"; then
                         ac_cv_occ_include_dir="$subdir";
                       fi
                     done] )
    if test "xNONE" = "x$ac_cv_occ_include_dir"; then
      AC_MSG_ERROR([Count not find include dir in: $occ_DIR])
    else
      OCC_INC_FLAG="-I${occ_DIR}/$ac_cv_occ_include_dir"
      if (test -f ${occ_DIR}/$ac_cv_occ_include_dir/oce-config.h); then
        ISOCE="TRUE"
      fi
    fi

    AC_CACHE_CHECK( [for 'lib' subdir of $occ_DIR],
                    [ac_cv_occ_lib_dir],
                    [ac_cv_occ_lib_dir=NONE
                     uname=`uname`
                     for subdir in lib ros/lib ros/${uname}/lib ros/$uname ; do
                       if test -d "${occ_DIR}/${subdir}"; then
                         ac_cv_occ_lib_dir="$subdir"
                         for file in ${occ_DIR}/${subdir}/libTKernel.* ; do
                           if test -f $file; then
                             break 2
                           fi
                         done
                       fi
                     done] )
    if test "xNONE" = "x$ac_cv_occ_lib_dir"; then
      AC_MSG_ERROR([Count not find lib dir in: $occ_DIR])
    else
      OCC_LIB_DIR="$occ_DIR/$ac_cv_occ_lib_dir"
      OCC_LIB_FLAG="-L$OCC_LIB_DIR"
    fi
  fi

  # Check of OCC is present and working

  # Save old value of these variables and update working ones
  old_CPPFLAGS="$CPPFLAGS"
  old_LDFLAGS="$LDFLAGS"
  CPPFLAGS="$CPPFLAGS ${OCC_INC_FLAG}"
  LDFLAGS="$LDFLAGS -L$OCC_LIB_DIR"

  # Check if 64-bit
  AC_MSG_CHECKING([if platform is 64-bit (-D_OCC64)])
  AC_TRY_COMPILE([],[int array[6-(int)sizeof(void*)];],[AC_MSG_RESULT(no)],
                 [AC_MSG_RESULT(yes); OCC_INC_FLAG="$OCC_INC_FLAG -D_OCC64"])

  # OCC requires some defines
  AC_LANG_PUSH(C++)
  AC_CHECK_HEADER([iostream],[OCC_INC_FLAG="$OCC_INC_FLAG -DHAVE_IOSTREAM"])
  AC_CHECK_HEADER([iostream.h],[OCC_INC_FLAG="$OCC_INC_FLAG -DHAVE_IOSTREAM_H"])
  AC_CHECK_HEADER([iomanip],[OCC_INC_FLAG="$OCC_INC_FLAG -DHAVE_IOMANIP"])
  AC_CHECK_HEADER([iomanip.h],[OCC_INC_FLAG="$OCC_INC_FLAG -DHAVE_IOMANIP_H"])
  AC_CHECK_HEADER([fstream],[OCC_INC_FLAG="$OCC_INC_FLAG -DHAVE_FSTREAM"])
  AC_CHECK_HEADER([fstream.h],[OCC_INC_FLAG="$OCC_INC_FLAG -DHAVE_FSTREAM_H"])
  AC_CHECK_HEADER([limits.h],[OCC_INC_FLAG="$OCC_INC_FLAG -DHAVE_LIMITS_H"])

  # Check for OCC headers Stadard_Version.hxx
  AC_CHECK_HEADER( [Standard_Version.hxx], [],
                 [AC_MSG_ERROR([OpenCascade config error:Standard_Version.hxx not found])] )

  # this will basically add -ldl at the end of dependency list for occ
  # questionable if this is the right solution
  AC_CHECK_LIB(dl, dlopen, LIBS="$LIBS -ldl")

  # Check if libTKernel.so contains function standard functions (sin, cos)
  # OCC 6.3 has build error where libTKernel.so requires libdl.so,
  #   but does not list that in the shared library dependencies.
  #   Try to work around this bug by detecting the need for -ldl.
  AC_CHECK_LIB( [TKernel], [sin],HAVE_OCC=yes,
                [unset ac_cv_lib_TKernel_sin
                 AC_CHECK_LIB( [TKernel], [cos],
                               [HAVE_OCC=yes; OCC_LIBS="$OCC_LIBS $LIBS"],
                               [HAVE_OCC=no],
                               [$LIBS] )
                ] )

  if test "$HAVE_OCC" != "no"; then
    # Common setup for tests below
    old_LIBS="$LIBS"
    CPPFLAGS="$CPPFLAGS $OCC_INC_FLAG"

    # Check if OpenCascade requires -lpthread
    AC_MSG_CHECKING([if OpenCascade requires -lpthread])
    LIBS="$OCC_LIBS $old_LIBS"
    AC_LINK_IFELSE(
      [AC_LANG_PROGRAM([#include "Standard_Mutex.hxx"], [Standard_Mutex mutex; mutex.TryLock();])],
      [AC_MSG_RESULT([no])],
      [# Try test again with pthreads library
        LIBS="$LIBS -lpthread"
        AC_LINK_IFELSE(
          [AC_LANG_PROGRAM([#include "Standard_Mutex.hxx"], [Standard_Mutex mutex; mutex.TryLock();])],
          [AC_MSG_RESULT([yes]); OCC_LIBS="$OCC_LIBS -lpthread"],
          [AC_MSG_ERROR([Cannot link libTKernel with Standard_Mutex])]
        )])

    HAVE_OCC_DEF="-DHAVE_OCC"

    # Check for IGES support
    AC_CHECK_LIB( [TKIGES], [igesread],
                  [HAVE_OCC_DEF="$HAVE_OCC_DEF -DHAVE_OCC_IGES"
                  OCC_LIBS="-lTKIGES -lTKXSBase $OCC_LIBS"],
                  [], [-lTKXSBase $OCC_LIBS] )

    # Check for STEP support
    AC_MSG_CHECKING([for OpenCascade STEP support (libTKSTEP)])
    LIBS="$OCC_STEP_LIBS $OCC_LIBS $old_LIBS"
    AC_LINK_IFELSE(
      [AC_LANG_PROGRAM([#include "STEPControl_Reader.hxx"],
                        [STEPControl_Reader reader;])],
      [HAVE_OCC_DEF="$HAVE_OCC_DEF -DHAVE_OCC_STEP"
        OCC_LIBS="$OCC_STEP_LIBS $OCC_LIBS"
        AC_MSG_RESULT([yes])],
      [AC_MSG_RESULT([no])])

    # Check for STL support
    AC_MSG_CHECKING([for OpenCascade STL support (libTKSTL)])
    LIBS="-lTKSTL $OCC_LIBS $old_LIBS"
    AC_LINK_IFELSE(
      [AC_LANG_PROGRAM([#include "StlAPI_Reader.hxx"],
                        [StlAPI_Reader reader;])],
      [HAVE_OCC_DEF="$HAVE_OCC_DEF -DHAVE_OCC_STL"
        OCC_LIBS="-lTKSTL $OCC_LIBS"
        AC_MSG_RESULT([yes])],
      [AC_MSG_RESULT([no])])

    # Restore original values of variables
    AC_LANG_POP(C++)
    LIBS="$old_LIBS"
    CPPFLAGS="$old_CPPFLAGS"
    LDFLAGS="$old_LDFLAGS"

    # Append to CGM global values
    CGM_EXT_LIBS="$CGM_EXT_LIBS $OCC_LIBS"
    CGM_EXT_LDFLAGS="$CGM_EXT_LDFLAGS $OCC_LIB_FLAG"
    CGM_EXT_INCLUDE="$CGM_EXT_INCLUDE $OCC_INC_FLAG"
    # NOTE: No CGM_EXT_LTFLAGS because OCC libs are .la files (not needed)
  fi
fi

# Export these variables as variables in Makefiles
AC_SUBST(OCC_INC_FLAG)
AC_SUBST(OCC_LIB_DIR)
AC_SUBST(OCC_LIB_FLAG)
AC_SUBST(OCC_LIBS)
AC_SUBST(ISOCE)
#AC_SUBST(CGM_OCC_LIB)
AC_SUBST(HAVE_OCC_DEF)

################################################################################
#                           Define variables for linking
################################################################################
AC_SUBST(CGM_EXT_LIBS)
AC_SUBST(CGM_EXT_LDFLAGS)
AC_SUBST(CGM_EXT_LTFLAGS)
AC_SUBST(CGM_EXT_INCLUDE)

# Allow "if build_OCC" in Makefile.am
AM_CONDITIONAL( build_OCC, [test "x$occ_DIR" != "xno"] )
AM_CONDITIONAL( build_FACET, [test "x$HAVE_OCC" != "xyes"] )
if (test "x$HAVE_OCC" != "xyes"); then
  AC_DEFINE(HAVE_FACET_ENGINE_ONLY,[1],[CGM Configured only with the Facet engine])
  PRIMARY_GEOMETRY_ENGINE="FACETS"
else # If other engines are available, modify appropriately
  PRIMARY_GEOMETRY_ENGINE="OCC"
fi
AC_SUBST(PRIMARY_GEOMETRY_ENGINE)

################################################################################
#                           Output Files
################################################################################
AC_SUBST(AM_CPPFLAGS)
AC_SUBST(AM_LDFLAGS)
AC_MSG_RESULT([CXXFLAGS = $CXXFLAGS])
AC_MSG_RESULT([AM_CPPFLAGS = $AM_CPPFLAGS])
AC_OUTPUT_COMMANDS( [if test -f src/init/cgm/CGMInitConfigure.h; then true; else echo "#define CGMA_INIT_EXPORT" > src/init/cgm/CGMInitConfigure.h; fi] )
AC_OUTPUT_COMMANDS( [if test -f src/util/cgm/CGMUtilConfigure.h; then true; else echo "#define CUBIT_UTIL_EXPORT" > src/util/cgm/CGMUtilConfigure.h; fi] )
AC_OUTPUT_COMMANDS( [if test -f src/geom/cgm/CGMGeomConfigure.h; then true; else echo "#define CUBIT_GEOM_EXPORT" > src/geom/cgm/CGMGeomConfigure.h; fi] )
AC_OUTPUT_COMMANDS( [if test -f itaps/CGMIGeomConfigure.h; then true; else echo "#define CGMA_IGEOM_EXPORT" > itaps/CGMIGeomConfigure.h; fi] )
AC_CONFIG_HEADERS([src/cgm/CGMConfig.h:config/CGMConfig.h.in])
AX_PREFIX_CONFIG_H([src/cgm/CGMConfig.h],[CGM],[src/cgm/CGMConfig.h])
AC_CONFIG_HEADERS(src/geom/parallel/cgm/CGMmpi_config.h)
AC_CONFIG_FILES(Makefile 
           src/Makefile
           src/util/Makefile
           src/util/cgm/Makefile
           src/geom/Makefile
           src/geom/cgm/Makefile
           src/geom/Cholla/Makefile
           src/geom/facet/Makefile
           src/geom/facetbool/Makefile
           src/geom/OCC/Makefile
           src/geom/parallel/Makefile
           src/geom/virtual/Makefile 
           src/init/Makefile
           src/init/cgm/Makefile
           compat/Makefile
           cgm.make:config/cgm.make.in
           CGMConfig.cmake:config/CGMConfig.cmake.in
           itaps/Makefile
           itaps/iGeom-Defs.inc
           test/Makefile
           tools/Makefile
           tools/mcnp2cad/Makefile
           test/TestConfig.h
           doc/cgm.dox
           )
# make distcheck will use this DISTCHECK_CONFIGURE_FLAGS
# variable to be passed to configure line
# some people include a lot of env vars here
# I think we need only those; only distcheck is affected by this
## original is commented out below; we use only a few
## for var in CC CFLAGS CPPFLAGS CXX CXXCPP LDFLAGS LIBS F90 FC F77; do
for var in CC CXX F90 FC F77 LDFLAGS LIBS; do
  eval isset=\${$var+set}
  if test "$isset" = 'set' ; then
    eval val=$`echo $var`
    DISTCHECK_CONFIGURE_FLAGS="$DISTCHECK_CONFIGURE_FLAGS $var=\"$val\""
  fi
done

AC_SUBST([DISTCHECK_CONFIGURE_FLAGS])

AC_OUTPUT
